<template>
  <div class="pan-page">
    <!-- 顶部导航栏 -->
    <div class="header">
      <div class="nav">
        <!-- 这里可以放一些按钮，如上传、新建文件夹等 -->

        <el-dropdown>
          <div class="upLoadFile">
            <el-upload
                class="upload-demo"
                :on-change="handleChange"
                :http-request="MulUpload"
                multiple
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :on-exceed="handleExceed"
            >
            <el-button type="primary" class="upLoad">
              <el-icon class="elIcon"><Upload /></el-icon>
              上传
            </el-button>
            </el-upload>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item>上传文件</el-dropdown-item>
              <el-dropdown-item>上传文件夹</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>

        <el-button type="primary" plain class="new" @click="dialogVisible=true">新建文件夹</el-button>
        <el-dialog
            v-model="dialogVisible"
            title="新建文件夹"
            width="500"
        >
          <el-input
            placeholder="请输入文件名"
            v-model="fileName"
          ></el-input>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="NewFolder">
                创建
              </el-button>
            </div>
          </template>
        </el-dialog>
        <el-button type="primary" plain class="new">新建在线文档</el-button>
        <el-button type="primary" plain class="new">云添加</el-button>
      </div>
    </div>
    <!-- 路径导航栏 -->
    <div class="breadcrumb">
      <el-breadcrumb separator="->">
        <el-breadcrumb-item @click="goToRoot">
          <span class="pathName allFile">全部文件</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item
            v-for="(folder, index) in path"
            :key="index"
            :to="folder.path"
            @click="navigateToFolder(index)"
        >
         <span class="pathName">{{ folder.fileName }}</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!-- 文件列表展示区域 -->
    <div class="content">
      <Table :tableData="tableData" @upDateTableData="updateTableData"/>
    </div>
  </div>
</template>

<script setup>
// 假设你已经封装了 FileTable 组件
import Table from "@/components/Table.vue";
import {getCurrentInstance, onMounted, ref, watch} from "vue";
import {onBeforeRouteUpdate, useRoute} from "vue-router";
import {getFile, getParentFile, newFolder} from "@/api/file.js";
import {Upload} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";

import eventBus from '@/utils/eventBus';
const proxy = getCurrentInstance();

const dialogVisible = ref(false);
const route = useRoute();
const tableData=ref([]);

const fileName = ref('');
const fileType=ref(null);

const path = ref([]); // 路径数组
const updateTableData=(file)=>{
  const newPath = [...path.value];
  newPath.push(file);
  path.value = newPath;
  console.log("路径数组",path.value);
  const data={
    pageSize:100,
    pageIndex:1,
    sidx:'',
    order:'',
    fileName:'',
    updateAt:'',
    folderId:file.fileId,
    fileType:'',
    isFolder:null,
    isValid:true
  }
  getFile(data).then(res=>{
    console.log(res.data);
    if(res.data.code===200){
      tableData.value = res.data.files.records.map(file => ({
        ...file,
        fileSize: formatFileSize(file.fileSize)
      }));
    }
    else {
      ElMessage({
        message:res.data.msg,
        type:'error'
      })
    }
  })
}

const fileMap={
  'image':1,
  'video':2,
  'all':null,
  'audio':4,
  'document':5,
  'other':6
}

//定义切片的大小
const chunkSize = 1024 * 1024 * 5; //以5M来分片
const handleChange=(file, fileList) =>{
  console.log("当前选择的文件对象:", file.raw);
  console.log("所有选择的文件列表:", fileList);
  eventBus.emit('file-added', file.raw);
  // eventBus.config.globalProperties.$emit('addFile', file.raw);
}
const MulUpload=()=>{

}
// 文件大小格式化
const formatFileSize = (size) => {
  if(size<=0) return '-';
  if (size < 1024) return `${size} B`;
  if (size < 1024 * 1024) return `${(size / 1024).toFixed(2)} KB`;
  if (size < 1024 * 1024 * 1024) return `${(size / (1024 * 1024)).toFixed(2)} MB`;
  return `${(size / (1024 * 1024 * 1024)).toFixed(2)} GB`;
};

const getFileTypeFromPath = (filePath) => {
  const fileMap = {
    'image': 1,
    'video': 2,
    'all': null,
    'audio': 4,
    'document': 5,
    'other': 6
  };
  return fileMap[filePath] || null;
};
const GetFileType=()=>{
  const data={
    sidx:'',
    order:'',
    fileName:'',
    fileType:fileType.value,
  };
  getParentFile(data).then(res=>{
    console.log(data);
    console.log("获取文件",res.data);
    if(res.data.code===200){
      tableData.value = res.data.files.map(file => ({
        ...file,
        fileSize: formatFileSize(file.fileSize) || '-'
      }));
    }
    else {
      proxy.$message({
        message:res.data.msg,
        type:'error'
      })
    }
  })
}

const GetFile = ()=>{
  const data={
    pageSize:100,
    pageIndex:1,
    sidx:'',
    order:'',
    fileName:'',
    updateAt:'',
    folderId:null,
    fileType:'',
    isFolder:null,
    isValid:true
  }
  getFile(data).then(res=>{
    console.log(res.data);
    if(res.data.code===200){
      tableData.value = res.data.files.records.map(file => ({
        ...file,
        fileSize: formatFileSize(file.fileSize)
      }));
    }
    else {
      ElMessage({
        message:res.data.msg,
        type:'error'
      })
    }
  })
}
const updatePath = (file) => {
  const newPath = path.value.slice();
  const existingIndex = newPath.findIndex(p => p.path === folderId);
  if (existingIndex === -1) {
    newPath.push({ name: folderName, path: folderId });
  }
  path.value = newPath;
};

const goToRoot = () => {
  path.value = [];
  GetFile();
};

const navigateToFolder = (index) => {
  const selectedFolder = path.value[index];
  path.value = path.value.slice(0, index + 1);
  const data = {
    sidx: '',
    order: '',
    fileName: '',
    fileType: fileType.value,
    folderId: selectedFolder.path
  };
  getFile(data).then(res => {
    if (res.data.code === 200) {
      tableData.value = res.data.files.map(file => ({
        ...file,
        fileSize: formatFileSize(file.fileSize)
      }));
    } else {
      ElMessage({
        message: res.data.msg,
        type: 'error'
      });
    }
  });
};
// 监听路由变化
watch(
    () => route.params.category,
    (newCategory) => {
      console.log(newCategory)
      fileType.value = getFileTypeFromPath(newCategory);
      console.log("filetype.value",fileType.value);
      if(fileType.value===null){
        GetFile();
      }
      else{
        GetFileType();
      }

    },
    { immediate: true } // 确保在组件挂载时也能触发
);

// 初次加载时获取文件
onMounted(() => {
  GetFile();
});

const NewFolder=()=>{
  dialogVisible.value=false;
  const data={
    folderName:fileName.value,
    targetFolderId:tableData.value[0].folderId,
  }
  newFolder(data).then(res=>{
    console.log(res.data);
    if(res.data.code===200){
      GetFile();
    }
    else {
      ElMessage({
        message:res.data.msg,
        type:'error'
      })
    }
  }).catch(error=>{
    console.log(error);
  })
}

</script>

<style scoped lang="scss">
.pan-page {
  display: flex;
  flex-direction: column;
  height: 100vh;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #eaeaea;

    .nav {
      display: flex;
      align-items: center;

      .el-button {
        margin-right: 10px;
      }
    }
  }

  .content {
    flex: 1;
    padding: 20px;
    overflow-y: auto;
    background-color: #ffffff;
  }
}
.upLoad{
  border-radius: 50px;
}
.elIcon{
  margin-right:5px;
}
.new{
  border-radius: 50px;
}
.breadcrumb {
  padding: 10px 20px;
  background-color: #f7f7f7;
  border-bottom: 1px solid #eaeaea;

  .el-breadcrumb {
    margin: 0;
  }

  .el-breadcrumb-item {
    &:hover {
      cursor: pointer !important;
    }
  }
}
.breadcrumb :hover{
  cursor: pointer;
  color: #ff0073;
}
.allFile{
  color:#05a1f5;
}

</style>
